package 力扣.数组.二维数组;

import java.util.Arrays;

public class 重塑矩阵566 {
    public static void main(String[] args) {
//        int[][] ints = new int[][]{{1, 2}, {3, 4}};
        int[][] ints = new int[][]{{1,2,3}, {4, 5,6},{7,8,9},{10,11,12}};
        int[][] res = matrixReshape(ints, 3, 4);
        System.out.println(Arrays.deepToString(res));
    }

    public static int[][] matrixReshape(int[][] nums, int r, int c) {
        int rows = nums.length;//获取二维数组的行数
        int cols = nums[0].length;//获取每一个行的元素个数
        if (rows * cols != r * c) {//元素个数不相等则肯定不能重塑
            return nums;
        }
        int[][] res = new int[r][c];
        int p = 0, q = 0;//使用新的下边p、q分别代表res数组的行、列
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                    int te = nums[i][j];
                    if (q >= c) {//代表一行元素全部填充完毕，进入下一行
                        q = 0;
                        p++;
                    }
                    res[p][q] = te;
                    q++;
            }
        }
        return res;
    }
}
